//
//  NetworkURLCache.m
//  OneStoreFramework
//
//  Created by huang jiming on 14-7-28.
//  Copyright (c) 2014年 OneStore. All rights reserved.
//

#import "NetworkURLCache.h"
#import <CoreCode/CoreCode.h>

@implementation NetworkURLCache

#pragma mark - Life Cycle

DEF_SINGLETON(NetworkURLCache)

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)aRequest {
    NSURLRequest *modifiedRequest = [self getModifiedRequest:aRequest];
    return [super cachedResponseForRequest:modifiedRequest];
}

- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse
                 forRequest:(NSURLRequest *)aRequest {
    NSURLRequest *modifiedRequest = [self getModifiedRequest:aRequest];
    [super storeCachedResponse:cachedResponse forRequest:modifiedRequest];
}

- (void)removeCachedResponseForRequest:(NSURLRequest *)request {
    NSURLRequest *modifiedRequest = [self getModifiedRequest:request];
    [super removeCachedResponseForRequest:modifiedRequest];
}

#pragma mark - Inner
/**
 *  功能:获取经过处理的request，把参数中跟签名、时间戳相关的参数及trader去掉
 *  aRequest:原request
 *  返回:经过处理的request
 */
- (NSURLRequest *)getModifiedRequest:(NSURLRequest *)aRequest {
    NSString *requestUrlStr = aRequest.URL.absoluteString;
    NSArray *componentArray = [requestUrlStr componentsSeparatedByString:@"?"];
    if (componentArray.count > 1) {
        NSString *headStr = componentArray.firstObject;
        NSString *queryUrl = [componentArray lastObject];
        NSArray *paramArray = [queryUrl componentsSeparatedByString:@"&"];
        NSMutableArray *modifiedParamArray = [@[] mutableCopy];
        for (NSString *paramStr in paramArray) {
            if (![paramStr hasPrefix:@"signature="] &&
                ![paramStr hasPrefix:@"signature_method="] &&
                ![paramStr hasPrefix:@"timestamp="] &&
                ![paramStr hasPrefix:@"trader=iosSystem"]) {
                if (paramStr.length > 0) {
                    [modifiedParamArray addObject:paramStr];
                }
            }
        }
        NSString *modifiedParamStr = [modifiedParamArray componentsJoinedByString:@"&"];
        
        NSString *modifiedUrlStr = nil;
        if (modifiedParamStr.length > 0) {
            modifiedUrlStr = [NSString stringWithFormat:@"%@?%@", headStr, modifiedParamStr];
        } else {
            modifiedUrlStr = headStr;
        }
        
        NSMutableURLRequest *modifiedRequest = [aRequest mutableCopy];
        modifiedRequest.URL = [NSURL URLWithString:modifiedUrlStr];
        return modifiedRequest;
        
    } else {
        return aRequest;
    }
}

@end
